﻿using FDStudio.Core.Runtime;
using FDStudio.Core.Serializer;

namespace FDStudio.Core.Extensions
{
    /*
     CreatedOn: 2018-01-25
     CreatedBy: Jackie Lee(天宇遊龍)
     */
    /// <summary>
    /// Json扩展
    /// </summary>
    public static class JsonExtension
    {
        /// <summary>
        /// 序列化为Json
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson(this object obj)
        {
            var serializer = RuntimeContext.Current.JsonSerializer;
            return serializer.Serialize(obj);
        }

        /// <summary>
        /// 反序列化为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T FromJson<T>(this string str)
        {
            if (str.IsNullOrEmpty())
            {
                return default(T);
            }
            var serializer = RuntimeContext.Current.JsonSerializer;
            return serializer.Deserialize<T>(str);
        }
    }
}
